<template>
  <div class="consultation-management-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h1>客服咨询管理</h1>
      <p>查看和管理用户咨询信息，支持筛选和回复操作</p>
    </div>

    <!-- 咨询表格卡片 -->
    <el-card class="consultation-table-card">
      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <el-input 
          placeholder="搜索咨询ID或问题内容" 
          v-model="searchQuery" 
          clearable
          size="small"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" size="small" @click="handleSearch" class="search-btn"></el-button>
          </template>
        </el-input>
        
       <el-select 
          v-model="queryPageParam.state" 
          placeholder="请选择订单状态"
          @change="handleSearch"
          size="small"
          class="status-select"
        >
          <el-option 
            v-for="item in statusOptions" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value"
          />
        </el-select>
      </div>

      <!-- 咨询表格 -->
      <el-table 
        :data="consultationList" 
        style="width: 100%"
        border
        :header-cell-style="{ background: '#f0f5ff', color: '#409eff', fontWeight: '500' }"
        :row-class-name="tableRowClassName"
        @row-click="handleRowClick"
        highlight-current-row
        :empty-text="consultationList.length === 0 ? '暂无咨询数据' : '加载中...'"
        class="consultation-table"
      >
        <el-table-column fixed prop="sqid" label="咨询ID" width="100" align="center" />
        <el-table-column prop="user.uname" label="咨询用户" width="120" align="center" />
        <el-table-column prop="shoe.sname" label="相关商品" width="150" align="center" />
        <el-table-column prop="sqquestion" label="咨询问题" min-width="200" align="left">
          <template #default="scope">
            <div class="question-content">{{ scope.row.sqquestion }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="sqanswer" label="回复内容" min-width="200" align="left">
          <template #default="scope">
            <div class="answer-content">
              {{ scope.row.sqanswer || '<未回复>' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.state)">
              {{ getStatusText(scope.row.state) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sqquestiontime" label="咨询时间" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.sqquestiontime) }}
          </template>
        </el-table-column>
        <el-table-column prop="sqanswertime" label="回复时间" width="180" align="center">
          <template #default="scope">
            {{ scope.row.sqanswertime ? formatDateTime(scope.row.sqanswertime) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column fixed="right" label="操作" min-width="160" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showOrderDetail(scope.row)" >
              <Edit class="mr-1" /> 查看
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)" >
              <Edit class="mr-1" /> 回复
            </el-button>
            
            <el-popconfirm 
              title="确定要删除此咨询记录吗?"
              confirm-button-text="是"
              cancel-button-text="否"
              icon-color="red"
              @confirm="handleDelete(scope.row.sqid)"
            >
              <template #reference>
                <el-button type="danger" size="small" class="delete-btn ml-2">
                  <Delete class="mr-1" /> 删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryPageParam.pageNum"
          v-model:page-size="queryPageParam.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="queryPageParam.recordCount"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="queryConsultations"
          @current-change="queryConsultations"
          class="pagination"
        />
      </div>
    </el-card>
  </div>
  

 <!-- 咨询详情对话框 -->
  <el-dialog 
    title="咨询详情" 
    v-model="detailVisible"
    width="70%"  
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <div class="inquiry-detail-container">
      <!-- 1. 咨询基础信息区域 -->
      <el-row :gutter="20" class="detail-section">
        <el-col :span="24">
          <h3 class="section-title">咨询基础信息</h3>
          <el-descriptions 
            border 
            column="3"
            :label-width="120"
          >
            <!-- 咨询状态展示，使用Vue3语法的函数调用 -->
            <el-descriptions-item label="咨询状态">{{ getInquiryStatusText(currentInquiry.state) }}</el-descriptions-item>
            <el-descriptions-item label="咨询ID">{{ formatNullValue(currentInquiry.sqid) }}</el-descriptions-item>
            <el-descriptions-item label="咨询问题">{{ formatNullValue(currentInquiry.sqquestion) }}</el-descriptions-item>
            <el-descriptions-item label="提问时间">{{ formatIsoDate(currentInquiry.sqquestiontime) }}</el-descriptions-item>
            <el-descriptions-item label="回答时间">{{ formatIsoDate(currentInquiry.sqanswertime) }}</el-descriptions-item>
            <el-descriptions-item label="咨询回答">{{ formatNullValue(currentInquiry.sqanswer) }}</el-descriptions-item>
            <el-descriptions-item label="咨询备注">{{ formatNullValue(currentInquiry.sqremarks) }}</el-descriptions-item>

          </el-descriptions>
        </el-col>
      </el-row>

      <!-- 2. 咨询用户信息区域 -->
      <el-row :gutter="20" class="detail-section">
        <el-col :span="24">
          <h3 class="section-title">咨询用户信息</h3>
          <el-descriptions 
            border 
            column="3" 
            :label-width="120"
          >
            <el-descriptions-item label="用户ID">{{ formatNullValue(currentInquiry.user?.uid) }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ formatNullValue(currentInquiry.user?.uname) }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ formatNullValue(currentInquiry.user?.utel) }}</el-descriptions-item>
            <el-descriptions-item label="用户性别">{{ formatNullValue(currentInquiry.user?.ugender || '未填写') }}</el-descriptions-item>
            <el-descriptions-item label="用户邮箱">{{ formatNullValue(currentInquiry.user?.uemail) }}</el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ formatIsoDate(currentInquiry.user?.uregtime) }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <!-- 3. 关联鞋子信息区域 -->
      <el-row :gutter="20" class="detail-section">
        <el-col :span="24">
          <h3 class="section-title">关联鞋子信息</h3>
          <el-descriptions 
            border 
            column="3" 
            :label-width="120"
          >
            <el-descriptions-item label="鞋子ID">{{ formatNullValue(currentInquiry.shoe?.sid) }}</el-descriptions-item>
            <el-descriptions-item label="鞋子名称">{{ formatNullValue(currentInquiry.shoe?.sname) }}</el-descriptions-item>
            <el-descriptions-item label="鞋子价格">{{ formatNullValue(currentInquiry.shoe?.sprices) ? '¥' + currentInquiry.shoe?.sprices : '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="发布时间">{{ formatIsoDate(currentInquiry.shoe?.spubtime) }}</el-descriptions-item>
            <el-descriptions-item label="生产厂商">{{ formatNullValue(currentInquiry.shoe?.sproducer) }}</el-descriptions-item>
            <el-descriptions-item label="适用性别">{{ formatNullValue(currentInquiry.shoe?.sgender || '通用') }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <el-button @click="detailVisible = false">关闭</el-button>
    </template>
  </el-dialog>

   <!-- 回复咨询对话框 -->
  <el-dialog 
    title="回复咨询" 
    v-model="answerVisible" 
    width="600px" 
    :center="true" 
    :close-on-click-modal="false" 
    :before-close="closeAnswerDialog"
  >
    <!-- 表单：仅包含“回复内容”输入框（核心修改字段） -->
    <el-form 
      ref="answerFormRef" 
      :model="answerForm" 
      :rules="answerRules" 
      label-width="120px"
    >
      <!-- 1. 不可修改的基础信息（展示用） -->
      <el-form-item label="咨询ID" disabled>
        <el-input v-model="currentAnswerData.sqid" readonly />
      </el-form-item>

      <el-form-item label="咨询问题" disabled>
        <el-input 
          v-model="currentAnswerData.sqquestion"  
          type="textarea" 
          rows="3" 
          readonly 
        />
      </el-form-item>
     

      <!-- 2. 可修改的回复内容（核心字段） -->
      <el-form-item label="回复内容" prop="sqanswer">
        <el-input 
          v-model="answerForm.sqanswer" 
          type="textarea" 
          rows="4" 
          placeholder="请输入回复内容" 
          maxlength="500" 
          show-word-limit 
        />
      </el-form-item>
    </el-form>

    <!-- 对话框底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeAnswerDialog">取消</el-button>
        <el-button type="primary" @click="submitAnswer">提交回复</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted,watch } from 'vue';
import { ElMessage, ElForm } from 'element-plus';
import { shoesInquiryQueryPage,deleteById,updateById } from '@/api/shoesInquiry';



// 表格数据和分页参数
const consultationList = ref([]);
const queryPageParam = ref({
     pageNum: 1,
     pageSize: 10,
    sqquestion:'',
    state: ''
 
});
const currentInquiry =ref({})
// 搜索和筛选条件
const searchQuery = ref('');
// 详情对话框相关
const detailVisible = ref(false);
const answerVisible = ref(false);
// 2. 当前要回复的咨询数据（存储从表格传递的row数据）
const currentAnswerData = ref({});
// 3. 回复表单数据：仅包含需要修改的核心字段（sqid定位数据，sqanswer回复内容）
const answerForm = ref({

});
// 4. 表单验证规则：确保回复内容不为空
const answerRules = reactive({
  sqanswer: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { min: 2, max: 500, message: '回复内容需在2-500字符之间', trigger: 'blur' }
  ]
});
// 5. 表单ref：用于验证和重置
const answerFormRef = ref(null);

// 修改品牌按钮点击（接收当前行数据）
const handleEdit = (row) => {
   currentAnswerData.value = { ...row };
  answerForm.value.sqid = row.sqid;
  answerForm.value.sqanswer = row.sqanswer;
  answerForm.value.sqquestion=row.sqquestion;
  answerVisible.value = true;

};
// 7. 关闭回复对话框：重置表单+隐藏弹窗
const closeAnswerDialog = () => {
  if (answerFormRef.value) {
    answerFormRef.value.resetFields(); // 清除表单验证状态
  }
  answerVisible.value = false;
};
// 8. 提交回复：调用接口修改sqanswer和state
const submitAnswer = async () => {
  // 第一步：表单验证
  if (!answerFormRef.value) return;
  try {
    await answerFormRef.value.validate(); // 触发必填项验证
  } catch (error) {
    ElMessage.warning('请完善回复内容后提交');
    return;
  }

  // 第二步：构造接口参数（仅传递需要修改的字段：sqid+sqanswer+state=1）
  const submitParams = {
    sqid: answerForm.value.sqid,          // 定位要修改的咨询记录
    sqanswer: answerForm.value.sqanswer,  // 新的回复内容（修改字段1）
    state: 1,                       // 回复后状态改为1（修改字段2）

  };

  // 第三步：调用接口提交修改
  try {
    console.log("这是answerForm——————》",answerForm.value)
      console.log("这是submitParams——————》",submitParams)
    await updateById(submitParams);
    // 回复成功：提示+关闭弹窗+刷新列表
    ElMessage.success('回复提交成功！');
    closeAnswerDialog();
    queryConsultations(); // 重新查询咨询列表，更新页面状态
  } catch (error) {
    ElMessage.error('回复提交失败：' + (error.message || '未知错误'));
  }
};


// 页面加载时查询数据
onMounted(() => {
  queryConsultations();
});

// 查询咨询列表
const queryConsultations = async () => {
    
      shoesInquiryQueryPage(queryPageParam.value.sqquestion,queryPageParam.value.pageNum, 
  queryPageParam.value.pageSize,queryPageParam.value.state)
    .then(data => {
      // 将数据赋值给数据模型
      consultationList.value = data.list || [];
      // 假设接口返回的分页信息包含总记录数
      queryPageParam.value.recordCount = data.pager?.recordCount || 0;
      console.log(consultationList, queryPageParam)
    })
    .catch(error => {
      ElMessage.error('获取订单列表失败：' + (error.message || '未知错误'));
    });
};

// 1. 防抖定时器（用于清除上一次的延迟查询）
let searchTimer = null;
// 4. 防抖搜索核心函数  增加 immediate 参数（默认 false）
const debounceSearch = async (immediate = false) => {
  // 第一步：清除上一次的定时器（防止重复触发）
  if (searchTimer) {
    clearTimeout(searchTimer);
  }

// 定义核心查询逻辑（抽成函数，避免重复代码）
  const doSearch = async () => {
    try {
      // 重置页码（搜索时从第1页开始）
      queryPageParam.value.pageNum = 1;
      // 赋值搜索参数
      const searchVal = searchQuery.value.trim();
      queryPageParam.value.sqquestion = searchVal;
      
      
      // 发起请求（await 等待结果）
        queryConsultations();

    } catch (err) {
      ElMessage.error('查询失败，请重试');
      console.error('搜索错误：', err);
    }
  };

  // 关键逻辑：根据 immediate 决定是否立即执行
  if (immediate) {
    // 手动触发：立即执行查询（无延迟）
    await doSearch();
  } else {
    // 自动输入：延迟 500ms 执行（防抖）
    searchTimer = setTimeout(doSearch, 500);
  }
};

    // 5. 监听输入框变化，自动触发防抖搜索
    watch(searchQuery, (newVal) => {
      // 输入变化时，立即执行防抖逻辑
      debounceSearch();
    }, {
      immediate: true // 初始加载时，若 searchQuery 有默认值，也触发一次查询
    });

// 搜索订单
const handleSearch = () => {
  debounceSearch(true); // 手动触发 → 立即执行
};



function showOrderDetail(Inquiry) {
  // 深拷贝用户对象，避免修改弹窗内容影响表格数据
  currentInquiry.value = JSON.parse(JSON.stringify(Inquiry))
 
  // 显示弹窗
  detailVisible.value = true
}



// 删除咨询记录
const handleDelete = async (sqid) => {
  try {
    await deleteById(sqid);
    ElMessage.success('删除成功');
    // 刷新列表
    queryConsultations();
  } catch (error) {
    ElMessage.error('删除失败：' + (error.message || '未知错误'));
  }
};

// 表格行样式
const tableRowClassName = ({ row }) => {
  // 未回复的咨询高亮显示
  return row.state === 0 ? 'warning-row' : '';
};

// 行点击事件
const handleRowClick = (row) => {
  // 点击行时可执行的操作，如选中行等
};

// 下拉列表选项（从步骤1引入或直接定义）
const statusOptions = [
  { label: "全部问题", value: '' },
  { label: "未回复", value: 0 },
  { label: "已回复", value: 1 },
 
];
// 状态文本映射
const getStatusText = (state) => {
  switch (state) {
    case 0: return '未回复';
    case 1: return '已回复';
    default: return '未知';
  }
};

// 状态标签类型映射
const getStatusTagType = (state) => {
  switch (state) {
    case 0: return 'warning'; // 未回复-警告色
    case 1: return 'success'; // 已回复-成功色
    default: return 'info';
  }
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '';
  // 处理字符串类型的日期
  if (typeof date === 'string') {
    // 尝试转换为Date对象
    const dateObj = new Date(date);
    if (!isNaN(dateObj.getTime())) {
      date = dateObj;
    } else {
      return date;
    }
  }
  
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};



// 空值处理函数
const formatNullValue = (value) => {
  return value === null || value === undefined || value === '' ? '-' : value;
};

// 时间格式化函数
const formatIsoDate = (isoTime) => {
  if (!isoTime) return '-';
  const date = new Date(isoTime);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};
// 咨询状态转换函数（重点调整部分）
const getInquiryStatusText = (state) => {
  // 状态映射表，可根据实际业务需求扩展
  const statusMap = {
    0: '未回答',
    1: '已回答',

  };
  // 处理未知状态
  return statusMap[state] !== undefined ? statusMap[state] : `未知状态(${state})`;
};

</script>

<style scoped>
.consultation-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #1f2329;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #6b7280;
}

.consultation-table-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  overflow: hidden;
}

.table-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.status-select, .date-picker {
  width: 200px;
}

.consultation-table {
  margin-bottom: 16px;
}

::v-deep .warning-row {
  background-color: #fffbeb;
}

.question-content, .answer-content {
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.consultation-detail-container {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  color: #1f2329;
  margin-bottom: 10px;
  padding-left: 5px;
  border-left: 3px solid #409eff;
}

.consultation-content, .answer-content {
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 4px;
  line-height: 1.8;
  min-height: 80px;
}

::v-deep .el-descriptions__cell {
  padding: 12px 10px;
}

::v-deep .el-descriptions__label {
  font-weight: 500;
}
.inquiry-detail-container {
  padding: 10px 0;
}
.detail-section {
  margin-bottom: 20px;
}
.section-title {
  font-size: 16px;
  font-weight: 700;
  color: #333;
  margin-bottom: 10px;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}
</style>
